/**
 * Importing the file below initializes the extension background.
 *
 * Warnings:
 * 1. Do not remove the import statement below. It is required for the extension to work.
 *    If you don't need createBridge(), leave it as "import '#q-app/bex/background'".
 * 2. Do not import this file in multiple background scripts. Only once!
 * 3. Import it in your background service worker (if available for your target browser).
 */
import { createBridge } from '#q-app/bex/background'
/**
 * Call useBridge() to enable communication with the app & content scripts
 * (and between the app & content scripts), otherwise skip calling
 * useBridge() and use no bridge.
 */
const bridge = createBridge({ debug: true })

//通知页面检测媒体元素
async function detectMediaElements() {
  try {
    // 通过 bridge 发送检测消息到内容脚本
    const portList = bridge.portList.filter((portName) => portName.startsWith('content@'))
    if (portList.length) {
      portList.forEach(async (port) => {
        await bridge.send({
          event: 'start-detect-page-medias',
          to: port,
        })
      })
      console.log('已发送音视频检测请求到标签页：', portList)
    } else {
      console.log('未发现已注册的网页。')
    }
  } catch (error) {
    console.error('发送检测请求失败:', error)
  }
}

// 监听获取当前标签页信息的请求
bridge.on('get-active-tab', async () => {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
    return tab
  } catch (error) {
    console.error('获取当前标签页信息失败:', error)
    return null
  }
})

// 监听请求转录事件
bridge.on('ask-for-transcription', async ({ payload }) => {
  console.log('收到转录请求', payload)
  bridge.send({
    event: 'start-transcription',
    to: payload.port,
    payload,
  })
})

chrome.action.onClicked.addListener(detectMediaElements)
